﻿Imports System.Text
Public Class frmMontaItensAvaliacao
    Inherits formPadrao
    Private WithEvents editingControl As TextBox
    Private cont As Integer = 0
    Private nomeDiretorio As String = Nothing
    Private teclouEnter As Boolean = False
    Private quantosEnter As Integer = 0

    Private Sub frmMontaItensAvaliacao_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Me.WindowState = FormWindowState.Maximized
            'generica.redimensionaControle(pnlDados)
            'generica.redimensionaControle(pnlItens)
            txtItens.Focus()
            gridDados.AutoGenerateColumns = False

        Catch ex As Exception
            generica.gravaErro(ex)

        End Try
    End Sub
    Private Sub populaTextBox()
        gridDados.Rows.Clear()
        gridDados.Visible = True
        txtTexto.Visible = False
        lbMensagem.Text = String.Empty

        Try

            If txtItens.Text.Equals(String.Empty) Then
                MsgBox("Favor informar ou colar os itens na janela em destaque", MsgBoxStyle.Exclamation)
                txtItens.Focus()
            Else

                If Not teclouEnter Or txtItens.Lines.Count = 1 Then
                    For Each linha As String In txtItens.Lines
                        gridDados.Rows.Add(linha.Trim, "")
                    Next
                Else

                    Dim contador As Integer = 0
                    Dim total As Integer = txtItens.Lines.Count
                    Dim texto As String = Nothing

                    For Each linha As String In txtItens.Lines

                        contador = contador + 1

                        If linha.ToString.Equals(String.Empty) Then
                            texto = texto & " " & linha.ToString.Trim
                            gridDados.Rows.Add(texto.Trim, "")
                            texto = String.Empty
                        Else
                            If contador = total Then
                                gridDados.Rows.Add(linha.Trim, "")
                                Exit For
                            Else
                                texto = texto & " " & linha.ToString.Trim
                            End If

                        End If

                    Next
                End If

                If gridDados.Rows.Count > 0 Then
                    gridDados.Focus()
                    gridDados.CurrentCell = gridDados(1, 0)
                End If

            End If
        Catch ex As Exception

            generica.gravaErro(ex)

        End Try
    End Sub

    Private Sub btnLimpar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLimpar.Click
        limpa(False)
        txtItens.Text = String.Empty
        gridDados.Rows.Clear()
        gridDados.Visible = True
        txtTexto.Visible = False
        lbMensagem.Text = String.Empty
    End Sub


    Private Sub editingControl_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles editingControl.KeyUp

        Dim texto As String = CType(sender, TextBox).Text
        Dim i As Integer = texto.IndexOf(",")
        Dim linha, coluna As Integer
        Dim ultimo As Integer = gridDados.Rows.Count


        linha = gridDados.CurrentCell.RowIndex + 1
        coluna = gridDados.CurrentCell.ColumnIndex

        If i > 0 Then
            cont = cont + 1

            If cont = 3 Then


                gridDados.Focus()

                If linha <> ultimo Then
                    gridDados.CurrentCell = gridDados(coluna, linha)
                End If
                cont = 0
            End If
        End If

    End Sub



    Private Sub TextboxNumeric_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)

        Dim nonNumberEntered As Boolean

        nonNumberEntered = True

        If (e.KeyChar >= Convert.ToChar(48) AndAlso e.KeyChar <= Convert.ToChar(57)) OrElse e.KeyChar = Convert.ToChar(8) OrElse e.KeyChar = Convert.ToChar(44) Then

            nonNumberEntered = False

        End If

        If nonNumberEntered = True Then

            ' Stop the character from being entered into the control

            ' since it is non-numerical.

            e.Handled = True

        Else

            e.Handled = False

        End If

    End Sub


    Private Sub btnCriaLista_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCriaLista.Click
        populaTextBox()
    End Sub

    Private Sub limpa(ByVal limpa As Boolean)
        teclouEnter = limpa
        quantosEnter = 0
    End Sub

    Private Sub btnWord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWord.Click
        If validaCampos() Then
            geraLaudo()
            limpa(False)
        Else
            MsgBox("Favor informar o valor do item")
            txtItens.Focus()
        End If
    End Sub

    Private Sub geraLaudo()
        Dim total As Double = 0
        Dim texto As New StringBuilder


        lbMensagem.Text = "O texto gerado já foi copiado para a área de transferência. Acesse o PCNET e tecle <CTRL + V>"
        Try

            texto.Append("DA AVALIAÇÃO")
            texto.Append(Environment.NewLine)
            texto.Append(Environment.NewLine)
            texto.Append("Com base nas informações contidas na requisição pericial e nas diversas pesquisas de mercado, aquilatou, ao final, para o objeto questionado, a seguinte valoração:")
            texto.Append(Environment.NewLine)
            texto.Append(Environment.NewLine)
            For Each row As DataGridViewRow In gridDados.Rows
                texto.Append(row.Cells("DESCRICAO").Value).Append(", avaliado no valor de ").Append(FormatCurrency(row.Cells("VALOR").Value)).Append(".")
                total = total + CType(row.Cells("VALOR").Value, Double)
                texto.Append(Environment.NewLine)
                texto.Append(Environment.NewLine)
            Next

            texto.Append("Desta forma, o valor total da presente avaliação corresponde a ")
            texto.Append(FormatCurrency(total)).Append(" (").Append(generica.extensoValor(total)).Append(").")
            texto.Append(" Dito valor por ser flutuável, é o que mais se aproxima do real pelo que pôde constar o Perito.")
            txtTexto.Text = texto.ToString
            '--------------------------------------------------------------------------------------------
            ' Copia o texto para a área de transferência
            '--------------------------------------------------------------------------------------------
            gridDados.Visible = False
            txtTexto.Visible = True

            Clipboard.SetDataObject(texto.ToString)


        Catch ex As Exception
            generica.gravaErro(ex)
            Exit Sub
        End Try
    End Sub


    Private Function validaCampos() As Boolean
        Dim valida As Boolean = False
        For Each row As DataGridViewRow In gridDados.Rows
            If (row.Cells(1).Value) = "" Then
                gridDados.CurrentCell = gridDados(1, row.Index)
                valida = False
                Exit For
            Else
                valida = True
            End If
        Next
        Return valida
    End Function

    Private Sub gridDados_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
        Try
            gridDados.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = generica.formataValorDataGrid(gridDados.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
        Catch ex As Exception
            generica.gravaErro(ex)
        End Try
    End Sub

    Private Sub gridDados_EditingControlShowing1(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs)
        If CInt((DirectCast((sender), System.Windows.Forms.DataGridView).CurrentCell.ColumnIndex)) = 1 Then

            AddHandler e.Control.KeyPress, AddressOf Me.TextboxNumeric_KeyPress

        End If

        editingControl = TryCast(e.Control, TextBox)

        If editingControl IsNot Nothing Then
            editingControl.CharacterCasing = CharacterCasing.Upper
        End If

        If CInt((DirectCast((sender), System.Windows.Forms.DataGridView).CurrentCell.ColumnIndex)) = 0 Then

            gridDados.Columns(0).ReadOnly = True

        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        gridDados.Visible = False
        txtTexto.Visible = True

    End Sub

    Private Sub txtItens_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtItens.KeyPress
        If e.KeyChar = Convert.ToChar(13) Then
            teclouEnter = True
            quantosEnter = quantosEnter + 1
        End If
    End Sub

    Private Sub txtItens_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtItens.TextChanged
        If teclouEnter And quantosEnter <= 1 Then
            'MsgBox("Para editar a lista deixe uma linha em branco entre os itens a serem avaliados")
        End If


    End Sub

    Private Sub gridDados_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles gridDados.EditingControlShowing
        If CInt((DirectCast((sender), System.Windows.Forms.DataGridView).CurrentCell.ColumnIndex)) = 1 Then

            AddHandler e.Control.KeyPress, AddressOf Me.TextboxNumeric_KeyPress

        End If

        editingControl = TryCast(e.Control, TextBox)

        If editingControl IsNot Nothing Then
            editingControl.CharacterCasing = CharacterCasing.Upper
        End If

        If CInt((DirectCast((sender), System.Windows.Forms.DataGridView).CurrentCell.ColumnIndex)) = 0 Then

            gridDados.Columns(0).ReadOnly = True

        End If
    End Sub

    Private Sub gridDados_KeyPress(sender As Object, e As KeyPressEventArgs) Handles gridDados.KeyPress

        Dim texto As String = CType(sender, TextBox).Text
        Dim i As Integer = texto.IndexOf(",")
        Dim linha, coluna As Integer
        Dim ultimo As Integer = gridDados.Rows.Count


        linha = gridDados.CurrentCell.RowIndex + 1
        coluna = gridDados.CurrentCell.ColumnIndex

        If i > 0 Then
            cont = cont + 1

            If cont = 3 Then


                gridDados.Focus()

                If linha <> ultimo Then
                    gridDados.CurrentCell = gridDados(coluna, linha)
                End If
                cont = 0
            End If
        End If
    End Sub


End Class